<template>
  <div class="permission-container">
    <div class="app-container">
      <!-- 表格 -->
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <el-button type="primary" size="small" @click="addClick('0',1)">添加权限</el-button>
        </div>
        <!-- row-key开启树形结构 -->
        <el-table row-key="id" border :data="list">
          <el-table-column label="名称" prop="name" />
          <el-table-column label="标识" prop="code" />
          <el-table-column label="描述" prop="description" />
          <el-table-column label="操作">
            <template #default="{row}">
              <el-button v-if="row.type===1" type="text" @click="addClick(row.id,2)">添加</el-button>
              <el-button type="text" @click="EditClick(row.id)">编辑</el-button>
              <el-button type="text" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <el-dialog :visible.sync="showDialog" title="弹层标题" @close="resetForm">
        <!-- 表单内容 -->
        <el-form ref="form" label-width="100px" :model="formData" :rules="rules">
          <el-form-item label="权限名称" prop="name">
            <el-input v-model="formData.name" />
          </el-form-item>
          <el-form-item label="权限标识" prop="code">
            <el-input v-model="formData.code" />
          </el-form-item>
          <el-form-item label="权限描述">
            <el-input v-model="formData.description" />
          </el-form-item>
          <el-form-item label="权限启用">
            <el-switch
              v-model="formData.enVisible"
              active-text="启用"
              active-value="1"
              inactive-text="不启用"
              inactive-value="0"
            />
          </el-form-item>
        </el-form>

        <template #footer>
          <div style="text-align: right;">
            <el-button @click="showDialog = false">取消</el-button>
            <el-button type="primary" @click="hSubmit">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { getPermissionList, addPermission, delPermission, getPermissionDetail, updatePermission } from '@/api/permissions'
import { tranListToTreeList } from '@/utils/departments'
export default {
  data() {
    // 权限名称校验
    const existNameValid = (rules, value, callback) => {
      // 获取点击的校验名称的pid
      const pid = this.formData.pid
      console.log(pid, 'pid')
      // 获取所有和他同级的校验name
      let brothers = this.list.filter(item => item.pid === pid)
      // 判断是否是编辑状态
      if (this.isEdit) {
        // 如果是编辑就剔除他自己的name再去校验
        brothers = brothers.filter(item => item.id !== this.id).map(item => item.name)
      } else {
        // 如果是添加就直接拿去校验
        brothers = brothers.map(item => item.name)
      }
      // 打印一下同级的name
      console.log(brothers, 'brothers')
      // 如果输入的value有和同级的name相同就返回校验失败如果没有相同的就callback
      if (brothers.includes(value)) {
        callback(new Error(`该权限${value}已经存在`))
      } else {
        callback()
      }
    }
    const existCodeValid = (rules, value, callback) => {
      let existCodeList = this.list.map(item => item.code)
      if (this.isEdit) {
        existCodeList = this.list.filter(item => item.id !== this.id).map(item => item.code)
      }
      console.log(existCodeList)
      if (existCodeList.includes(value)) {
        callback(new Error(`${value}已存在`))
      } else {
        callback()
      }
    }
    return {
      id: '',
      list: [],
      formData: {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      },
      rules: {
        name: [
          { required: true, message: '请输入权限名称', trigger: 'blur' },
          { validator: existNameValid, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入权限标识', trigger: 'blur' },
          { validator: existCodeValid, trigger: 'blur' }
        ]
      },
      showDialog: false,
      isEdit: false
    }
  },
  created() {
    this.loadPermissionList()
  },
  methods: {
    // 编辑的数据回显
    async loadPermissionDetail(id) {
      try {
        const res = await getPermissionDetail(id)
        console.log(res)
        this.formData = res.data
      } catch (error) {
        console.log(error)
      }
    },
    // 编辑的事件
    async hEdit() {
      const res = await updatePermission(this.formData)
      console.log(res, 'updatePermission')
      this.showDialog = false

      this.loadPermissionList()
    },
    // 编辑的按钮点击之后触发的事件
    async EditClick(id) {
      this.id = id
      this.isEdit = true
      this.showDialog = true
      this.loadPermissionDetail(id)
    },
    hDel(id) {
      this.$confirm('您确认要删除吗？').then(async() => {
        const res = await delPermission(id)
        console.log(res)
        this.loadPermissionList()
      }).catch(err => console.log(err))
    },
    resetForm() {
      this.formData = {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      }
      this.$refs.form.resetFields()
    },
    async hAdd() {
      const res = await addPermission(this.formData)
      console.log(res, 'addPermission')
      this.showDialog = false

      this.loadPermissionList()
    },
    hSubmit() {
      this.$refs.form.validate((valid) => {
        if (!valid) return new Error('校验失败')
        this.isEdit ? this.hEdit() : this.hAdd()
      })
    },
    addClick(pid, type) {
      this.formData.pid = pid
      this.formData.type = type
      this.showDialog = true
      this.isEdit = false
    },
    async loadPermissionList() {
      try {
        const res = await getPermissionList()
        console.log('getPermissionList', res)
        this.list = tranListToTreeList(res.data)
        // 保存数据
      } catch (err) {
        console.log('getPermissionList', err)
      }
    }

  }
}
</script>
